const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    currentData: 0, 
    selectPerson: true,
    isplay:false,
    userInfo: app.globalData.userInfo,
     
    headImg: app.globalData.userInfo.avatarUrl, //用户头像
    nickName: app.globalData.userInfo.nickName, // 昵称
    activity:{
     
    },
    activityid:"",
    time:{},
    isshowregisterlists:false,
    animationData:{},
    stopBtn: true,//动画未执行完之前禁用按钮
    resgiterlist:[],
    offset:1,
    isloading:false,
    shareuserID:"",
    channelID:"",
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var activityid="" ,userID="",channelID="";
    var scene = decodeURIComponent(options.scene);
    var params = scene.split("&");
    if(scene && params.length>1){
     
      console.log(params);
      if (params.length == 1) {

        activityid = params[0].split("=")[1];
      } else if (params.length == 2) {
        activityid = params[0].split("=")[1];
        userID = params[1].split("=")[1];
      } else if (params.length == 3) {
        activityid = params[0].split("=")[1];
        userID = params[1].split("=")[1];
        channelID = params[2].split("=")[1];
      } 
      console.log(activityid);
      console.log(userID);

      this.setData({activityid:activityid,shareuserID:userID,channelID:channelID});
    }
   else if(options.activityid){
    activityid = options.activityid;
    channelID = options.channelID;//1
    userID = options.userID;
    this.setData({activityid:activityid,shareuserID:userID,channelID:channelID});
  
    }
    if (!app.checkislogin()) {
      wx.showToast({
        title: '请先登陆',
        icon: "none"
      })
      wx.navigateTo({
        url: '../login/login?url='+'/pages/activity/activity?activityid='+activityid,
      })
      return;
    }

  

  },

  onShow:function(){

    if (!app.checkislogin()) {
     
      return;
    }

    var activityid = this.data.activityid;

    this.setData({
      userInfo: app.globalData.userInfo,
      headImg: app.globalData.userInfo.avatarUrl, //用户头像
      nickName: app.globalData.userInfo.nickName, // 昵称
    });
 
 
    if(activityid){
     
      this.getactivity(activityid);
    }
    else{
       wx.navigateBack();
       return ;
    }

   

  },


  onHide:function(){
    this.cleartime();
  },

  onUnload:function(){
    this.cleartime();
  },


       /**
   * 用户点击右上角分享
   */
  /*
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:  app.globalData.userInfo.nickName + "--喊你一起来报名--"+  that.data.activity.name + '--活动报名-- ' +  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      path: '/pages/activity/activity?activityid='+that.data.activity.activityid+ "&userID=" + app.globalData.userInfo.userID +"&channelID="+that.data.channelID, // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:that.data.activity.thumb_url,
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(shareObj);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容
     
    }
    // 返回shareObj
    console.log(shareObj);
    return shareObj;
  },
*/
   //打开playerscorecard 页面 
   _opencourseNavgate (e) {
    e = e.currentTarget.dataset.address;  
    console.log(e);
    /*wx.getLocation({
      type: 'wgs84', 
      success: function (res) {
        wx.openLocation({//​使用微信内置地图查看位置。
          latitude: e.latitude,//要去的纬度-地址
          longitude: e.longitude,//要去的经度-地址
          name: e.name,
          address:e.address
        })
      }
    })*/
      
  },

  share:function(){

  
    var qrcode = this.selectComponent("#qrcode");
    qrcode.loading();
    var shareTitle = "高球尝鲜体验券";
    var shareeventTitle = this.data.activity.name;
    var shareCoverImg =  this.data.activity.thumb_url;

    var data = {
      path: 'pages/activity/activity',//'' pages/Schedul/index,
      scene: 'aid=' + this.data.activityid + "&uid=" + app.globalData.userInfo.userID +"&cid="+this.data.channelID,
    };

    app.getQrcode(data,function(res){
      qrcode.createQrcode(shareTitle, shareCoverImg, res,shareeventTitle);
    },function(){

    })

    

   // app.requestdata(app.globalData.interfacegetQrcode,
    //  data,
   //   function (res) {
    //    console.log(res);
    //    var shareQrImg = res.data.trim();

   //     qrcode.createQrcode(shareTitle, shareCoverImg, shareQrImg);
  //    },
  //    function (res) {
   //     console.log(res);

   //   },
   // )
  },

  play:function(){
    this.setData({isplay:true})
  },

  pause:function(){
    this.setData({isplay:false});

  },
  //获取当前滑块的index
  bindchange: function(e) {
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },
  //点击切换，滑块index赋值
  checkCurrent: function(e) {
    const that = this;

    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {

      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },

  getactivity:function(){
      wx.showLoading({
        title: '正在加载',
      });
      var that = this;
      app.getactivityinfo(this.data.activityid,this.data.shareuserID,this.data.channelID,function(res){
        console.log(res.data.data.activity);
          if(res.data.data){
            //res.data.data.activity.payurl = 'https://mapp.scoringchina.com/gplanetpay.jpg';
            that.setData({activity:res.data.data.activity});
            if(that.data.activity.channelID){
            that.setData({channelID:that.data.activity.channelID});
            }
            that.opentime();
          }
      },function(){wx.hideLoading();})
  },

  opentime(){
    var that=this;
    var endtime = this.data.activity.endtime;

    this.data.intervarID= setInterval(function () {
      
      var leftTime = ((new Date(endtime)) - (new Date())); //计算剩余的毫秒数 
      var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
      days = that.checkTime(days);
      hours = that.checkTime(hours);
      minutes = that.checkTime(minutes);
      seconds = that.checkTime(seconds);
      var time={};
      time.days=(days)?days:0;
      time.hours=hours;
      time.minutes=minutes;
      time.seconds=seconds;

      that.setData({
        time: time
      })
     // console.log(time);
      if (days == '00' && hours == '00' && minutes == '00' && seconds=='00')
      {
        clearInterval(that.data.intervarID);

        
      }
    }, 1000
    )
  },

  cleartime(){
    clearInterval(this.data.intervarID);
  },

  checkTime:function(e){
    //console.log(e);
    if(e<0){
      return e* (-1);
    }
    else{
      return e;
    }
  },

  call: function () {
    wx.makePhoneCall({
        phoneNumber: '13902294637',
        success: function () {
            console.log('拨打电话成功！')
        },
        fail: function () {
            console.log('拨打电话失败！')
        }
    })
  },

  goback:function(){
    wx.switchTab({
      url: '../index/index',
    })
  },

  openregsiter:function(){
      wx.navigateTo({
        url: './signup/signup?activityid=' + this.data.activity.activityid,
      })
  }
  ,

  openimage:function(e){
    var src = e.currentTarget.dataset.src;
    console.log(e);
    wx.previewImage({
      urls: [src],
    })
  },

  refreshregisterlists(){
    this.setData({offset:1});
    this.getregisterlists();
  },

  getregisterlists(){

    if(this.data.isloading){
      return ;
    }
    this.setData({isloading:true});
      var that = this;
      app.getrgelistsperson(that.data.activityid,that.data.offset,function(res){
          if(res.data.errorcode.code=="ok"){
              console.log("getregisterlists");
              if(res.data.data && res.data.data.length>0 )
              if(that.data.offset == 1){
                 that.setData({resgiterlist:res.data.data,offset: that.data.offset+1});
              }
              else{
                  var resgiterlist = that.data.resgiterlist;
                  resgiterlist = resgiterlist.concat(res.data.data);
                  that.setData({resgiterlist:resgiterlist,offset: that.data.offset+1});
              }
              
          }
          
      },function(){
        console.log("isloading:false");
        that.setData({isloading:false});
      });

    
  },

  showregisterlist:function(){
      var ishow = this.data.isshowregisterlists;
      if(ishow){
        
        this.hideContent();
      }
      else{
        this.getregisterlists();
        this.showContent();
       
      }
      this.setData({
        isshowregisterlists:!ishow
      });
  },

  showContent: function (e) {
    // 用that取代this，防止setTimeout内使用this出错
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
        // 动画持续时间
        duration: 500,
        // 定义动画效果，当前是匀速
        timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    //用step()完成一个动画， 高度为0，透明度为不可见
    animation.height("0").opacity(0).step()
    // 用setData改变当前动画
    that.setData({
        // 通过export()方法导出数据
        animationData: animation.export(),
        // 改变显示条件
        choose: true
    })
    // 设置setTimeout来改变高度以及透明度，实现有感觉的展开
    setTimeout(function () {
        animation.height("550rpx").opacity(1).step({ duration: 500 })
        that.setData({
            animationData: animation.export(),
        })
    }, 50)
    //在动画时间禁用按钮
    setTimeout(function () {
        that.setData({
            stopBtn: false
        })
    }, 500)
},

// 隐藏
hideContent: function (e) {
    var that = this;
    var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'linear'
    })
    that.animation = animation
    animation.height(0).opacity(0).step({ duration: 500 })
    that.setData({
        animationData: animation.export()
    })
    setTimeout(function () {
        animation.height("550rpx").step();
        that.setData({
            animationData: animation.export(),
            choose: false,
        })
    }, 500)
    //收回动画开始禁用按钮
    that.setData({
        stopBtn: true,
    })
},
downloadfile:function(e){

  var file = e.currentTarget.dataset.payurl;
  var filePath = wx.env.USER_DATA_PATH + '/payqrcode.jpg';
  console.log(file);
  wx.downloadFile({//下载
    url: file,//服务器上的pdf地址
    success: function (res) {
      wx.saveFile({
        tempFilePath: res.tempFilePath || res.filePath,
        filePath: filePath,
        success:(fileres)=>{
          console.log(fileres);
          var filerespath = fileres.savedFilePath
          wx.previewImage({
            urls: [filerespath],
          })
        },
        fail:(faileres)=>{
          wx.showToast({
            title: faileres.errMsg,
            duration:2000,
          })
        }
      })
     
    }
  })
},

})